package com.tanhua.back.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tanhua.back.entity.Admin;
import com.tanhua.back.exception.BusinessException;
import com.tanhua.back.mapper.AdminMapper;
import com.tanhua.back.service.AdminService;
import com.tanhua.back.utils.AppJwtUtil;
import com.tanhua.back.utils.Constants;
import com.tanhua.back.utils.ThreadLocalUtil;
import com.tanhua.back.vo.AdminVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @author shiqiang
 * @version 1.0
 * @date 2022/5/11 15:53
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements AdminService {
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 后台登陆
     * @param map
     * @return
     */
    @Override
    public Map<String, String> login(Map<String, String> map) {
        //1.获取请求参数
        String username= map.get("username");
        String password = map.get("password");
        password= DigestUtils.md5DigestAsHex(password.getBytes());
        String verificationCode = map.get("verificationCode");
        String uuid = map.get("uuid");
        //2.检验验证码是否正确
        String key= Constants.CAP_CODE+uuid;
        String value=redisTemplate.opsForValue().get(key);
        if (StringUtils.isEmpty(value)){
            throw new BusinessException("验证码失效");
        }
        if (!StringUtils.pathEquals(verificationCode,value)){
            throw new BusinessException("验证码错误");
        }
        redisTemplate.delete(key);
        //3.根据用户表查询admin
        LambdaQueryWrapper<Admin> wrapper= new LambdaQueryWrapper<>();
        wrapper.eq(Admin::getUsername, username);
        Admin admin = this.getOne(wrapper);
        if (ObjectUtils.isEmpty(admin)){
            throw new BusinessException("用户名不存在");
        }
        if (!StringUtils.pathEquals(password,admin.getPassword())){
            throw new BusinessException("用户名或密码错误");
        }
        //4.生成token
        String token = AppJwtUtil.getToken(admin.getId(),admin.getUsername());
        //5.构造返回
        Map<String,String> remap= new HashMap<>();
        remap.put("token",token);
        return remap;
    }

    /**
     *
     * 后台登出
     */
    @Override
    public void logout() {

    }

    /**
     * 查询用户基本信息
     */
    @Override
    public AdminVo profile() {
        //1.获取当前用户登陆id
        Long id = ThreadLocalUtil.getId();
        Admin admin = this.getById(id);
        //构造vo
        return AdminVo.init(admin);
    }
}

